import httplib
import random
import sys
import time

def httpStressTest(iterations, pause):
    '''
    Performs a stress test of the _Flagship Jean_ test server.
    iterations : (int)   number of requests to be sent
    pause      : (float) time between requests, in seconds
    '''

    random.seed()

    URLs = [ "/mmdk/rails/events/search?query=un",
             "/mmdk/rails/events/search?query=ski",
             "/mmdk/rails/events/search?query=2424",
             "/mmdk/rails/events/search?query=jean",
             "/mmdk/rails/events/search?query=phalanx",
             "/mmdk/rails/events/search?query=3510",
             "/mmdk/rails/events/search?query=3510",
             "/mmdk/rails/", ]

    failures = 0

    for i in range(0,iterations):
        server = httplib.HTTPConnection("senatedev.union.rpi.edu")
        server.connect()

        server.request("GET", URLs[random.randint(0,len(URLs)-1)])
        response = server.getresponse()

        if response.status != 200: # If not HTTP OK
            failures += 1
            print "%s %s" % (response.status, response.reason)

        server.close()

        time.sleep(pause)

    return failures

if __name__ == "__main__":
    failures = httpStressTest(int(sys.argv[1]), float(sys.argv[2]))

    if failures != 0:
        print "Total failures: %d" % failures
